package com.anrongtec.zcpt.adapter;

import android.content.Context;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.model.StatementData;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.jiakaiyang.library.easyform.tools.Constant;
import com.jiakaiyang.library.easyform.view.EFFormView;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：liuhui on 2017/2/18 16:00
 * 邮箱：liu594545591@126.com
 * 描述：DataStateAdapter
 */

public class DataStateAdapter extends BaseAdapter {
    private Context context;
    private List<StatementData> lvData;
    private ViewHolder holder;

    public DataStateAdapter(Context context, List<StatementData> lvData) {
        this.context = context;
        this.lvData = lvData;
    }

    @Override
    public int getCount() {
        return lvData.size() > 0 ? lvData.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return lvData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_rv_datas_form, parent, false);
            holder = new ViewHolder();
            holder.formView1 = (EFFormView) convertView.findViewById(R.id.fv_data_statement1);
            holder.formView2 = (EFFormView) convertView.findViewById(R.id.fv_data_statement2);
            holder.barChart = (BarChart) convertView.findViewById(R.id.bc_data_statement);
            holder.pieChart = (PieChart) convertView.findViewById(R.id.pc_data_statement);
            holder.lineChart = (LineChart) convertView.findViewById(R.id.lc_data_statement);
            holder.formTitle1 = (TextView) convertView.findViewById(R.id.tv_form_title1);
            holder.formTitle2 = (TextView) convertView.findViewById(R.id.tv_form_title2);
            holder.chartTitle = (TextView) convertView.findViewById(R.id.tv_chart_title);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final StatementData data = lvData.get(position);
//        holder.formView1.setList(data.getSparsePeople1());
        KLog.e("111111" + data.toString());
        List<Map<String, Object>> datas = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            Map map = new HashMap();
            map.put(Constant.KEY.KEY_DATA, i + "");
            datas.add(map);
        }
        holder.formView1.setData(datas);
        holder.formView1.fillForm();
        //设置每一条点击变色
        holder.formView1.setRowClickChange();
        //设置第一行不可点击，用于设置表头
        holder.formView1.setRowClickable(0, false);
//        ViewTreeObserver vto = holder.formView1.getViewTreeObserver();
//        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//            public boolean onPreDraw() {
//                holder.formView1.getViewTreeObserver().removeOnPreDrawListener(this);
//                int height = holder.formView1.getMeasuredHeight();
//                int width = holder.formView1.getMeasuredWidth();
//                holder.formView1.init(width, height);
//                holder.formView1.setRowAndColText(data.getAveragePeople(), data.getAveragePeoples());
//                return true;
//            }
//        });
//        holder.formView2.setList(data.getSparsePeople2());
//        ViewTreeObserver vto2 = holder.formView2.getViewTreeObserver();
//        vto2.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//            public boolean onPreDraw() {
//                holder.formView2.getViewTreeObserver().removeOnPreDrawListener(this);
//                int height = holder.formView2.getMeasuredHeight();
//                int width = holder.formView2.getMeasuredWidth();
//                holder.formView2.init(width, height);
//                holder.formView2.setRowAndColText(data.getTablePeople(), data.getTablePeoples());
//                return true;
//            }
//        });
        holder.formTitle1.setText(data.getAveragePeopleTitle());
        holder.formTitle2.setText(data.getTablePeopleTitle());
        holder.chartTitle.setText(data.getAverageMonthPeople());
        showBarChart(holder.barChart, getBarData(4, 100));
        showPieChart(holder.pieChart, getPieData(4, 100));
        showLineChart(holder.lineChart, getLineData());
        return convertView;
    }

    final class ViewHolder {
        TextView formTitle1;
        TextView formTitle2;
        TextView chartTitle;
        EFFormView formView1;
        EFFormView formView2;
        BarChart barChart;
        PieChart pieChart;
        LineChart lineChart;
    }

    /**
     * @param count 分成几部分
     * @param range
     */
    private PieData getPieData(int count, float range) {

        ArrayList<String> xValues = new ArrayList<String>();  //xVals用来表示每个饼块上的内容

        for (int i = 0; i < count; i++) {
//            xValues.add("Quarterly" + (i + 1));  //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
            xValues.add("第一季度");  //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
            xValues.add("第二季度");  //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
            xValues.add("第三季度");  //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
            xValues.add("第四季度");  //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
        }

        ArrayList<Entry> yValues = new ArrayList<Entry>();  //yVals用来表示封装每个饼块的实际数据

        // 饼图数据
        /**
         * 将一个饼形图分成四部分， 四部分的数值比例为14:14:34:38
         * 所以 14代表的百分比就是14%
         */
        float quarterly1 = 8;
        float quarterly2 = 7;
        float quarterly3 = 10;
        float quarterly4 = 12;

        yValues.add(new Entry(quarterly1, 0));
        yValues.add(new Entry(quarterly2, 1));
        yValues.add(new Entry(quarterly3, 2));
        yValues.add(new Entry(quarterly4, 3));

        //y轴的集合
        PieDataSet pieDataSet = new PieDataSet(yValues, "全年比例抓获"/*显示在比例图上*/);
        pieDataSet.setSliceSpace(0f); //设置个饼状图之间的距离

        ArrayList<Integer> colors = new ArrayList<Integer>();

        // 饼图颜色
        colors.add(Color.rgb(205, 205, 205));
        colors.add(Color.rgb(114, 188, 223));
        colors.add(Color.rgb(255, 123, 124));
        colors.add(Color.rgb(57, 135, 200));

        pieDataSet.setColors(colors);

        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        float px = 5 * (metrics.densityDpi / 160f);
        pieDataSet.setSelectionShift(px); // 选中态多出的长度

        PieData pieData = new PieData(xValues, pieDataSet);

        return pieData;
    }

    private LineData getLineData() {
        //模拟一个x轴的数据  12/1 12/2 ... 12/7
        ArrayList<String> xValues = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            xValues.add(i + "月");
        }

        Log.e("wing", xValues.size() + "");


        //模拟一组y轴数据(存放y轴数据的是一个Entry的ArrayList) 他是构建LineDataSet的参数之一

        ArrayList<Entry> yValue = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            yValue.add(new Entry(i, i));
        }

        //构建一个LineDataSet 代表一组Y轴数据 （比如不同的彩票： 七星彩  双色球）
        LineDataSet dataSet = new LineDataSet(yValue, "平均抓获人数");

        //模拟第二组组y轴数据(存放y轴数据的是一个Entry的ArrayList) 他是构建LineDataSet的参数之一

        ArrayList<Entry> yValue1 = new ArrayList<>();

        yValue1.add(new Entry(7, 0));
        yValue1.add(new Entry(11, 1));
        yValue1.add(new Entry(3, 2));
        yValue1.add(new Entry(5, 3));
        yValue1.add(new Entry(4, 4));
        yValue1.add(new Entry(3, 5));
        yValue1.add(new Entry(6, 6));
        yValue1.add(new Entry(7, 7));
        yValue1.add(new Entry(4, 8));
        yValue1.add(new Entry(7, 9));
        yValue1.add(new Entry(8, 10));
        yValue1.add(new Entry(8, 11));


        Log.e("wing", yValue.size() + "");

        //构建一个LineDataSet 代表一组Y轴数据 （比如不同的彩票： 七星彩  双色球）

        LineDataSet dataSet1 = new LineDataSet(yValue1, "抓获人数");
        dataSet1.setColor(Color.BLACK);
        //构建一个类型为LineDataSet的ArrayList 用来存放所有 y的LineDataSet   他是构建最终加入LineChart数据集所需要的参数
        ArrayList<LineDataSet> dataSets = new ArrayList<>();

        //将数据加入dataSets
        dataSets.add(dataSet);
        dataSets.add(dataSet1);

        //构建一个LineData  将dataSets放入
        LineData lineData = new LineData(xValues, dataSets);

        return lineData;
    }

    private BarData getBarData(int count, float range) {
        ArrayList<String> xValues = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            xValues.add("第" + (i + 1) + "季度");
        }

        ArrayList<BarEntry> yValues = new ArrayList<BarEntry>();

        for (int i = 0; i < count; i++) {
            float value = (float) (Math.random() * range/*100以内的随机数*/) + 3;
            yValues.add(new BarEntry(value, i));
        }

        // y轴的数据集合
        BarDataSet barDataSet = new BarDataSet(yValues, "季度抓获比例");

        barDataSet.setColor(Color.rgb(114, 188, 223));

        ArrayList<BarDataSet> barDataSets = new ArrayList<BarDataSet>();
        barDataSets.add(barDataSet); // add the datasets

        BarData barData = new BarData(xValues, barDataSets);

        return barData;
    }

    private void showBarChart(BarChart barChart, BarData barData) {
        barChart.setDrawBorders(false);  ////是否在折线图上添加边框

        barChart.setDescription("");// 数据描述

        // 如果没有数据的时候，会显示这个，类似ListView的EmptyView
        barChart.setNoDataTextDescription("You need to provide data for the chart.");

        barChart.setDrawGridBackground(false); // 是否显示表格颜色
        barChart.setGridBackgroundColor(Color.WHITE & 0x70FFFFFF); // 表格的的颜色，在这里是是给颜色设置一个透明度

        barChart.setTouchEnabled(true); // 设置是否可以触摸

        barChart.setDragEnabled(true);// 是否可以拖拽
        barChart.setScaleEnabled(true);// 是否可以缩放

        barChart.setPinchZoom(false);//

//      barChart.setBackgroundColor();// 设置背景

        barChart.setDrawBarShadow(true);

        barChart.setData(barData); // 设置数据

        Legend mLegend = barChart.getLegend(); // 设置比例图标示

        mLegend.setForm(Legend.LegendForm.CIRCLE);// 样式
        mLegend.setFormSize(6f);// 字体
        mLegend.setTextColor(Color.BLACK);// 颜色

//      X轴设定
//      XAxis xAxis = barChart.getXAxis();
//      xAxis.setPosition(XAxisPosition.BOTTOM);

        barChart.animateX(2500); // 立即执行的动画,x轴
    }

    private void showPieChart(PieChart pieChart, PieData pieData) {
        pieChart.setHoleColorTransparent(true);

        pieChart.setHoleRadius(60f);  //半径
        pieChart.setTransparentCircleRadius(64f); // 半透明圈
        //pieChart.setHoleRadius(0)  //实心圆

        pieChart.setDescription("测试饼状图");

        // mChart.setDrawYValues(true);
        pieChart.setDrawCenterText(true);  //饼状图中间可以添加文字

        pieChart.setDrawHoleEnabled(true);

        pieChart.setRotationAngle(90); // 初始旋转角度

        // draws the corresponding description value into the slice
        // mChart.setDrawXValues(true);

        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(true); // 可以手动旋转

        // display percentage values
        pieChart.setUsePercentValues(true);  //显示成百分比
        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);

        // add a selection listener
//      mChart.setOnChartValueSelectedListener(this);
        // mChart.setTouchEnabled(false);

//      mChart.setOnAnimationListener(this);

        pieChart.setCenterText("季度抓获比例");  //饼状图中间的文字

        //设置数据
        pieChart.setData(pieData);

        // undo all highlights
//      pieChart.highlightValues(null);
//      pieChart.invalidate();

        Legend mLegend = pieChart.getLegend();  //设置比例图
        mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);  //最右边显示
//      mLegend.setForm(LegendForm.LINE);  //设置比例图的形状，默认是方形
        mLegend.setXEntrySpace(7f);
        mLegend.setYEntrySpace(5f);

        pieChart.animateXY(1000, 1000);  //设置动画
        // mChart.spin(2000, 0, 360);
    }

    private void showLineChart(LineChart mLineChart, LineData lineData) {
        XAxis xAxis = mLineChart.getXAxis();

        //设置X轴的文字在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        //设置描述文字
        mLineChart.setDescription("年度曲线图");
        mLineChart.setDragEnabled(false);
        mLineChart.setScaleEnabled(false);

        //将数据插入
        mLineChart.setData(lineData);
    }

}
